package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;

import com.itheima.exception.MemberDelfailException;

import com.itheima.pojo.Member;

import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.*;
import java.text.SimpleDateFormat;


@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;


    @Autowired
    private JedisPool jedisPool;


    //根据手机号查询会员信息
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    @Override
    public void add(Member member) {
        String password = member.getPassword();
        if (password != null) {
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    /**
     * 根据月份查询会员数量
     * @param months
     * @return
     */
    @Override
    public List<Integer> findCountByMonth(List<String> months) {
        List<Integer> list = new ArrayList<>();
        for (String month : months) {
            month = month + ".31";
            Integer memberCount = memberDao.findMemberCountBeforeDate(month);
            list.add(memberCount);
        }
        return list;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<Member> page = memberDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Member> rows = page.getResult();
        for (Member row : rows) {
            Date birthday = row.getBirthday();
            if(birthday==null){
                continue;
            }
            int year = birthday.getYear();
            int month = birthday.getMonth();
            int day = birthday.getDay();
            Date date = new Date();
            int year1 = date.getYear();
            int month1 = date.getMonth();
            int day1 = date.getDay();
            int age = year1 - year;
            if(month<=month1){
                if(day<=day1){
                    age++;
                }
            }
            row.setAge(age);
        }
        return new PageResult(total, rows);
    }

    @Override
    public List<Map<String,String>> findAllHealThmanagerName() {
        List<String> list = memberDao.findAllHealThmanagerName();
        List<Map<String,String>> mapList = new ArrayList<>();
        for (String s : list) {
            Map<String,String> map = new HashMap<>();
            map.put("value",s);
            mapList.add(map);
        }
        return mapList;
    }


    public Member findById(Integer id) {
        Member member = memberDao.findById(id);
        if(null==member.getHealthmanager_name()||("".equals(member.getHealthmanager_name()))){
            member.setHealthmanager_name("无");
        }
        return member;
    }

    public void edit(Member member) {
        memberDao.edit(member);
    }

    @Override
    public void deleteById(Integer id) throws Exception{
        Integer count = memberDao.findCountByMemberId(id);
        if(null!=count&&count>0){
            throw new MemberDelfailException();
        }
        memberDao.deleteById(id);
    }

    @Override
    public List<Map<String,Object>> findByIds(String[] ids) {
        List<Map<String,Object>> list = new ArrayList<>();
        for (String id : ids) {
            Map<String, Object> map = new HashMap<>();
            Member member = memberDao.findByIds(Integer.parseInt(id));
            map.put("member",member);
            List<String> adderss = memberDao.findAddressByMemberId(Integer.parseInt(id));
            map.put("adderss",adderss);
            List<String> setlist = memberDao.findSetmealByMemberId(Integer.parseInt(id));
            String sname="";
            if(setlist.size()>0 && setlist!=null){
                for (int i = 0; i < setlist.size(); i++) {
                    String s1 = (String) setlist.get(i);
                    sname=sname+","+s1;
                }
            }
            map.put("sname",sname);

            List<String> checkgroups = memberDao.findCheckgroupByMemberId(Integer.parseInt(id));
            map.put("checkgroups",checkgroups);
            List<String> checkitems = memberDao.findCheckitemByMemberId(Integer.parseInt(id));
            map.put("checkitems",checkitems);
            for (Object checkitem : checkitems) {
                System.out.println(checkitem.toString());
            }

            list.add(map);
        }
        return list;
    }

    @Override
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCounts = new ArrayList<>();
        if (months != null && months.size() > 0) {
            for (String month : months) {//2019.01
                String endTime = month + ".31";
                Integer memberCount = memberDao.findMemberCountBeforeDate(endTime);
                memberCounts.add(memberCount);
            }
        }
        return memberCounts;
    }
    //查询各个年龄段的会员数量
    public Map findMemberCountByDate() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(date));
        String baby = sdf.format(new Date(date.getTime() - 60 * 60 * 24 * 365 * 10 * 1000L));
        String young = sdf.format(new Date(date.getTime() - 60 * 60 * 24 * 365 * 30 * 1000L));
        String middle = sdf.format(new Date(date.getTime() - 60 * 60 * 24 * 365 * 50 * 1000L));
        Integer babyCount = memberDao.findMemCountAfterDate(baby);
        Integer youngCount = memberDao.findMemCountBetweenDate(young,baby);
        Integer middleCount = memberDao.findMemCountBetweenDate(middle,young);
        Integer oldCount = memberDao.findMemCountBeforeDate(middle);
        List<Integer> count = new ArrayList<>();
        count.add(babyCount);
        count.add(youngCount);
        count.add(middleCount);
        count.add(oldCount);
        List<String> crowd = new ArrayList<>();
        crowd.add("幼儿");
        crowd.add("青年");
        crowd.add("中年");
        crowd.add("老年");
        Map<String, List> map = new HashMap<>();
        map.put("crowd", crowd);
        map.put("count", count);
        return map;
    }


    @Override
    public void edit(Member member, Integer validateCode) {
        String oldTelephone = memberDao.findTelephoneById(member.getId());
        String newTelephone = member.getPhoneNumber();
        //如果有修改手机号的操作，需要验证验证码
        if (!newTelephone.equals(oldTelephone)){
            String validateCodeRedis = jedisPool.getResource().get(oldTelephone + RedisMessageConstant.SENDTYPE_EDIT);
            if (validateCode != null && String.valueOf(validateCode).equals(validateCodeRedis)){
                memberDao.editTelephone(newTelephone,String.valueOf(member.getId()));
            }
        }
        memberDao.editBaseInfo(member);
    }

}
